package cn.basic.org.controller;

import cn.basic.auth.annotation.BasicPermission;
import cn.basic.auth.vo.query.EmployeeRoleQuery;
import cn.basic.auth.vo.result.MenuVo;
import cn.basic.org.domain.Employee;
import cn.basic.org.domain.EmployeeInfo;
import cn.basic.org.dto.EmployeeDTO;
import cn.basic.org.dto.EmployeeInfoDTO;
import cn.basic.org.service.IEmployeeService;
import cn.basic.org.service.IInfoService;
import cn.basic.org.vo.query.DepartmentQuery;
import cn.basic.org.vo.query.KeyQuery;
import cn.basic.org.vo.query.PageQuery;
import cn.basic.org.vo.result.DepartmentVo;
import cn.basic.org.vo.result.EmployeeInfoVo;
import cn.basic.org.vo.result.EmployeeVo;
import cn.basic.org.vo.result.Switch;
import cn.basic.utils.AjaxResult;
import cn.basic.utils.BasicMap;
import cn.basic.utils.PageList;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * description: EmployeeController <br>
 * date: 2023/3/1 16:59 <br>
 * author: ZhaoLc <br>
 * version: 1.0 <br>
 */
@RestController
@RequestMapping("/employee")
@Api(value = "员工API",description="员工相关的CRUD功能")
@BasicPermission(name = "员工管理",desc = "【员工管理相关权限】")
public class EmployeeController {

    @Autowired
    IEmployeeService employeeService;

    @Autowired
    IInfoService infoService;


    @BasicPermission(name = "员工新增修改",desc = "【员工管理新增修改权限】")
    @RequestMapping(value = "/save",method = RequestMethod.PUT)
    public AjaxResult addOrUpdate(@RequestBody EmployeeDTO employeeDTO){
        try{
            Employee employee = employeeDTO.getEmployee();
            if(Objects.nonNull(employee.getId())){
                employeeService.update(employee);
            }else {
                employeeService.add(employee);
            }
            return AjaxResult.me().setMessage("保存成功");
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败！").setSuccess(false);
        }
    }

    @RequestMapping(value = "/getAll",method = {RequestMethod.POST,RequestMethod.GET})
    public AjaxResult getAll(){
        try {
            List<EmployeeVo> all = employeeService.getAll();
            return AjaxResult.me().setObject(all).setMessage(null);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败！").setSuccess(false);
        }
    }

    @BasicPermission(name = "员工删除",desc = "【员工管理删除权限】")
    @RequestMapping(value = "/delete/{id}",method = {RequestMethod.POST,RequestMethod.GET})
    public AjaxResult deleteById(@PathVariable("id") Long id){
        try {
            employeeService.deleteById(id);
            return AjaxResult.me().setMessage("删除成功！");
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败！").setSuccess(false);
        }
    }

    @BasicPermission(name = "员工分页查询",desc = "【员工管理分页查询权限】")
    @RequestMapping(method = RequestMethod.POST)
    public AjaxResult pageList(@RequestBody PageQuery query){
        try {
            PageList<EmployeeVo> list = employeeService.pageList(query);
            return AjaxResult.me().setObject(list).setMessage(null);
        } catch (Exception e) {
            return AjaxResult.me().setMessage(e.getMessage()).setSuccess(false);
        }
    }

    @BasicPermission(name = "员工根据ID查询",desc = "【员工管理ID查询权限】")
    @RequestMapping(value = "/getById/{id}",method = {RequestMethod.GET})
    public AjaxResult getById(@PathVariable Long id) {
        try {
            EmployeeVo employeeVo = employeeService.getVoById(id);
            return AjaxResult.me().setObject(employeeVo).setMessage(null);
        } catch (Exception e) {
            return AjaxResult.me().setMessage(e.getMessage()).setSuccess(false);
        }
    }

    @BasicPermission(name = "员工批量删除",desc = "【员工管理批量删除权限】")
    @RequestMapping(value = "/deleteBatch",method = {RequestMethod.PATCH})
    public AjaxResult deleteBatch(@RequestBody List<Long> ids){
        try {
            employeeService.deleteBatch(ids);
            return AjaxResult.me().setMessage("删除成功！");
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("批量删除失败！").setSuccess(false);
        }
    }

    @BasicPermission(name = "员工获取角色",desc = "【员工管理获取角色权限】")
    @RequestMapping(value = "/getRoleById/{id}",method = {RequestMethod.GET})
    public AjaxResult getRoleById(@PathVariable Long id){
        try {
            List<Long> ids = employeeService.getRoleById(id);
            return AjaxResult.me().setMessage(null).setObject(ids);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("查询失败！").setSuccess(false);
        }
    }

    @BasicPermission(name = "员工授予角色",desc = "【员工管理授予角色权限】")
    @RequestMapping(value = "/grantedRoleById",method = {RequestMethod.POST})
    public AjaxResult getRoleById(@RequestBody EmployeeRoleQuery employeeRoleQuery){
        try {
            employeeService.grantedRoles(employeeRoleQuery);
            return AjaxResult.me().setMessage("授权成功");
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("授权失败！").setSuccess(false);
        }
    }

    //@BasicPermission(name = "员工查询详细信息",desc = "【员工管理查询详细信息权限】")
    @RequestMapping(value = "/getInfoById/{id}",method = {RequestMethod.GET})
    public AjaxResult getInfoById(@PathVariable Long id){
        try {
            EmployeeInfoVo employeeInfoVo = employeeService.getInfoById(id);
            return AjaxResult.me().setMessage(null).setObject(employeeInfoVo);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("查询失败！").setSuccess(false);
        }
    }

    //@BasicPermission(name = "员工详细信息保存",desc = "【员工管理详细信息保存权限】")
    @RequestMapping(value = "/info/save",method = {RequestMethod.POST})
    public AjaxResult save(@RequestBody EmployeeInfoDTO employeeInfoDTO){
        try {
            employeeService.update(employeeInfoDTO.getEmployee(employeeInfoDTO));
            // 如果个人信息为空则添加
            if(Objects.nonNull(employeeService.getInfoById(employeeInfoDTO.getId()).getId())){
                employeeService.updateInfo(employeeInfoDTO.getEmployeeInfo(employeeInfoDTO));
            } else {
                employeeService.addInfo(employeeInfoDTO.getEmployeeInfo(employeeInfoDTO));
            }
            return AjaxResult.me().setMessage("保存成功！");
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存失败！").setSuccess(false);
        }
    }

   
    @RequestMapping(value = "/avatarUpLoad",method = RequestMethod.POST)
    public String  updateAvatar(MultipartFile file, HttpServletRequest req) throws Exception{
        System.out.println(file.toString());;
        //判断文件类型
        String pType=file.getContentType();
        pType=pType.substring(pType.indexOf("/")+1);
        if("jpeg".equals(pType)){
            pType="jpg";
        } else if("png".equals(pType)){
            pType="png";
        }
        String imagePath = infoService.updateAvatar(file,req);
        // 返回新的头像地址
        return imagePath;
    }

    @RequestMapping(value = "/avatarDownLoad/{id}",method = RequestMethod.GET,produces = "image/jpeg")
    public void avatarDownLoad(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response){
        // 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        String headImage = employeeService.getVoById(id).getHeadImage();
        File file = new File(path+headImage);
        ServletOutputStream outputStream = null;
        try {
            BufferedImage image = ImageIO.read(file);
            outputStream = response.getOutputStream();
            // 输出流输出图片，格式为jpg
            ImageIO.write(image, "jpg",outputStream);
            outputStream.flush();
        } catch (IOException e) {
            // 设置默认头像
            File file1 = new File("src/main/resources/image/error_user.jpg");
            try {
                BufferedImage image = ImageIO.read(file1);
                outputStream = response.getOutputStream();
                // 输出流输出图片，格式为jpg
                ImageIO.write(image, "jpg",outputStream);
                outputStream.flush();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            if(null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
